package cn.zhage.aimin.ds.translate;

import cn.zhage.aimin.ds.annotation.DictTranslate;
import cn.zhage.aimin.ds.dict.service.DictService;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.context.annotation.Lazy;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;

/**
 * @author 武天奇
 * @version 1.0
 */
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
@RequiredArgsConstructor(onConstructor = @__(@Lazy))
public class DictTeanslateInterceptor implements Interceptor {

    private final DictService dictService;
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //1.查询出数据来
        Object result = invocation.proceed();
        //2.遍历字段，是否有注解
        if(result instanceof List) {
            for (Object obj : (List<?>) result) {
                Class<?> clazz = obj.getClass();
                Field[] declaredFields = clazz.getDeclaredFields();
                for (Field field : declaredFields) {
                    DictTranslate annotation = field.getAnnotation(DictTranslate.class);
                    if (annotation != null) {
                        String targetField = annotation.valueTo();
                        field.setAccessible(true);
                        Object value = field.get(obj);
                        Field declaredField = clazz.getDeclaredField(targetField);
                        String dictName = dictService.getById((int) value).getDictName();
                        declaredField.setAccessible(true);
                        declaredField.set(obj, dictName);
                    }
                }
            }
        }
        return null;
    }
}
